//
//  ITReplacingResourceURLProtocol.m
//  InduceTool
//
//  Created by 魏延龙 on 2020/8/3.
//  Copyright © 2020 魏延龙. All rights reserved.
//  另一种方式
/*
 记得注册 http https
 + (void)wk_registerScheme:(NSString*)scheme;
 + (void)wk_unregisterScheme:(NSString*)scheme;
 */

#import "ITReplacingResourceURLProtocol.h"

static NSString* const FilteredKey = @"FilteredKey";

@implementation ITReplacingResourceURLProtocol


+ (BOOL)canInitWithRequest:(NSURLRequest *)request{
    NSString* extension = request.URL.pathExtension;
    NSString *lastPath = request.URL.lastPathComponent;
    BOOL canReplace = NO;
    if ([extension isEqualToString:@"css"]) {
        if ([lastPath containsString:@"normalize"]) {
            canReplace = YES;
        }
    }
    else if ([extension isEqualToString:@"js"]) {
        if ([lastPath containsString:@"jquery"]) {
            canReplace = YES;
        }
    }
    return canReplace;
}

//这个方法就是返回规范的request
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request{
    return request;
}

- (void)startLoading{
    NSMutableURLRequest* request = self.request.mutableCopy;
    [NSURLProtocol setProperty:@YES forKey:FilteredKey inRequest:request];
    NSString *lastPath = request.URL.lastPathComponent;
    NSURLResponse* response;
    NSData* data;
    if ([lastPath containsString:@"normalize"]) {
        data = [NSData dataWithContentsOfFile:[NSBundle.mainBundle pathForResource:@"normalize.min" ofType:@"css" inDirectory:@"Resource/lib"]];
        response = [[NSURLResponse alloc] initWithURL:self.request.URL MIMEType:@"text/css" expectedContentLength:data.length textEncodingName:nil];
    }
    else if ([lastPath containsString:@"jquery"]) {
        data = [NSData dataWithContentsOfFile:[NSBundle.mainBundle pathForResource:@"jquery-3.4.1.min" ofType:@"js" inDirectory:@"Resource/lib"]];
        response = [[NSURLResponse alloc] initWithURL:self.request.URL MIMEType:@"application/x-javascript" expectedContentLength:data.length textEncodingName:nil];
    }
    [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed];
    [self.client URLProtocol:self didLoadData:data];
    [self.client URLProtocolDidFinishLoading:self];

}
@end
